package com.derbysoft.lowcostadapter.web.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import java.io.*;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
 * Created by: jason
 * Date: 2012-09-29
 */
public class BuilderNumberInterceptor extends AbstractInterceptor {
    private static Log logger = LogFactory.getLog(BuilderNumberInterceptor.class);
    private static final String MANIFEST_MF = "/META-INF/MANIFEST.MF";
    private static final String BUILD_NUMBER_ATTRIBUTE = "Build-Number";
    private static final String EMPTY_BUILD_NUMBER = "DEVELOP";

    @Override
    public String intercept(ActionInvocation invocation) {
        invocation.getInvocationContext().getSession().put("buildNumber", getBuildNumber());
        try {
            return invocation.invoke();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public String getBuildNumber() {
        try {
            return getAttribute(BUILD_NUMBER_ATTRIBUTE);
        } catch (IOException e) {
            StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            logger.error(writer.toString());
        }
        return EMPTY_BUILD_NUMBER;
    }

    private String getAttribute(String attribute) throws IOException {
        File manifestFile = new File(ServletActionContext.getServletContext().getRealPath(MANIFEST_MF));
        if(!manifestFile.exists()){
            return "DEVELOPMENT";
        }
        Manifest mf = new Manifest();
        mf.read(new FileInputStream(manifestFile));
        Attributes attributes = mf.getMainAttributes();
        return attributes.getValue(attribute);
    }
}
